const websocketService = require('../services/wsService');
const Device = require('../models/DeviceModel'); // 确保路径正确

// 获取所有设备
const getDevices = async (req, res) => {
  try {
    const devices = await Device.find().lean();
    // console.log("取得的设备",devices)
    res.json({ code: 0, status: 'success', message: '获取设备成功', data: devices });
  } catch (error) {
    res.status(500).json({ message: '获取设备失败', error: error.message });
  }
};

// 添加新设备，没用到
const addGatherDevice = async (req, res) => {
  const { deviceName, accounts } = req.body; // 从请求体中获取设备名称和账号数组

  try {
    const newDevice = new Device({ deviceName, accounts }); // 创建新的 GatherDevice 实例
    const savedDevice = await newDevice.save(); // 保存到数据库
    res.status(201).json({ message: '添加设备成功', data: savedDevice });
  } catch (error) {
    let errorMessage = error.message;
    if (error.name === 'MongoError' && error.code === 11000) {
      errorMessage = '已存在相同设备名称';
    }
    res.status(500).json({ message: '添加设备失败', error: errorMessage });
  }
};

// 批量删除设备
const deleteDevices = async (req, res) => {
  const { deviceNames } = req.body; // 设备名称数组
  console.log("删除设备",deviceNames)
  if (!Array.isArray(deviceNames) || deviceNames.length === 0) {
    return res.status(400).json({ message: '未选择设备' });
  }

  try {
    const result = await Device.deleteMany({ deviceName: { $in: deviceNames } });
    res.json({ message: `${result.deletedCount} 个设备已删除` });
  } catch (error) {
    res.status(500).json({ message: '删除设备失败', error: error.message });
  }
};

// 指定账号执行任务
const accountStartTask = async (req, res) => {
  const { deviceName,taskParams,duration } = req.body; // 设备名称数组

  try {

    let message = {
      type: 'accountStartGatherTask',
      data: {
        "taskParams": taskParams,
      }
    }
    console.log("传输任务")
    websocketService.sendMessage(deviceName, message);

    res.json({ message: '执行任务成功' });
  } catch (error) {
    res.status(500).json({ message: '执行任务失败', error: error.message });
  }

};

// 指定账号停止任务
const accountStopTask = async (req, res) => {
  const { parentId, accountInfo } = req.body; // 设备名称数组

  try {

    let message = {
      type: 'accountStopGatherTask',
      data: accountInfo
    }

    websocketService.sendMessage(parentId, message);

    res.json({ message: '执行任务成功' });
  } catch (error) {
    res.status(500).json({ message: '执行任务失败', error: error.message });
  }

}

module.exports = {
  getDevices,
  addGatherDevice,
  deleteDevices,
  accountStartTask,
  accountStopTask
};
